package scenic.study.arithmetic.queue;

import java.util.Iterator;

/**
 * Created by scenic on 2017/2/14.
 */
public class LinkedQueue<T> implements QueueInterface<T>{

    private Node first;
    private Node last;

    private int N;

    @Override
    public void enqueue(T t) {
        Node node = new Node();
        node.t = t;
        if(first == null && last == null) {
            first = last = node;
        }else {
            last.next = node;
            last = node;
        }
        N++;
    }

    @Override
    public T dequeue() {
        T t = first.t;
        first = first.next;
        N--;
        if(isEmpty()){
            last = null;
        }
        return t;
    }

    @Override
    public int size() {
        return N;
    }

    @Override
    public boolean isEmpty() {
        return N == 0;
    }

    @Override
    public Iterator<T> iterator() {

        return new Iterator<T>() {
            Node first = LinkedQueue.this.first;

            @Override
            public boolean hasNext() {
                return first != null;
            }

            @Override
            public T next() {
                T t = first.t;
                first = first.next;
                return t;
            }
        };
    }



    private class Node {
        private Node next;
        private T t;
    }

}
